package com.budwk.app.sys.commons.task.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.fetchdata.models.FetchData_emergency;
import com.budwk.app.fetchdata.services.FetchdataEmergencyService;
import com.budwk.app.miniapp.utils.AddressUtils;
import com.budwk.app.miniapp.utils.HttpUtils;
import com.budwk.starter.email.EmailSendServer;

import com.budwk.starter.job.annotation.SJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;


import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Slf4j
@IocBean(name = "pullEmergencyInformationService",singleton = false)
public class PullEmergencyInformationService {

    @Inject
    private FetchdataEmergencyService wxSpiderEmergencyInformationService;

    @Inject
    private EmailSendServer emailSendServer;

    @Inject("taskQueryExecutor")
    private ThreadPoolExecutor taskQueryExecutor;
    @Inject
    private PropertiesProxy propertiesProxy;

    private final static Map<String, String> typeMap = new HashMap<>();

    static {
        typeMap.put("11B01_BLUE","台风（蓝色预警）");
        typeMap.put("11B03_BLUE","暴雨（蓝色预警）");
        typeMap.put("11B04_BLUE","暴雪（蓝色预警）");
        typeMap.put("11B05_BLUE","寒潮（蓝色预警）");
        typeMap.put("11B06_BLUE","大风（蓝色预警）");
        typeMap.put("11B07_BLUE","沙尘暴（蓝色预警）");
        typeMap.put("11B09_BLUE","高温（蓝色预警）");
        typeMap.put("11B11_BLUE","干热风（蓝色预警）");
        typeMap.put("11B14_BLUE","雷电（蓝色预警）");
        typeMap.put("11B15_BLUE","冰雹（蓝色预警）");
        typeMap.put("11B16_BLUE","霜冻（蓝色预警）");
        typeMap.put("11B17_BLUE","大雾（蓝色预警）");
        typeMap.put("11B19_BLUE","霾（蓝色预警）");
        typeMap.put("11B20_BLUE","雷雨大风（蓝色预警）");
        typeMap.put("11B21_BLUE","道路结冰（蓝色预警）");
        typeMap.put("11B22_BLUE","干旱（蓝色预警）");
        typeMap.put("11B25_BLUE","火险（蓝色预警）");

        typeMap.put("11B85_BLUE","雷雨强风（蓝色预警）");
        typeMap.put("11B58_BLUE","雷暴大风（蓝色预警）");
        typeMap.put("11B52_BLUE","雷雨大风（蓝色预警）");
        typeMap.put("11B51_BLUE","沙尘（蓝色预警）");
        typeMap.put("11B37_BLUE","地质灾害（蓝色预警）");
        typeMap.put("11B86_BLUE","低温凝冻（蓝色预警）");
        typeMap.put("11D08_BLUE","地质灾害气象风险（蓝色预警）");
        typeMap.put("11A51_BLUE","发布山洪灾害（蓝色预警）");

        typeMap.put("11B41_BLUE","森林草原火险（蓝色预警）");

        typeMap.put("11B01_YELLOW","台风（黄色预警）");
        typeMap.put("11B03_YELLOW","暴雨（黄色预警）");
        typeMap.put("11B04_YELLOW","暴雪（黄色预警）");
        typeMap.put("11B05_YELLOW","寒潮（黄色预警）");
        typeMap.put("11B06_YELLOW","大风（黄色预警）");
        typeMap.put("11B07_YELLOW","沙尘暴（黄色预警）");
        typeMap.put("11B09_YELLOW","高温（黄色预警）");
        typeMap.put("11B11_YELLOW","干热风（黄色预警）");
        typeMap.put("11B14_YELLOW","雷电（黄色预警）");
        typeMap.put("11B15_YELLOW","冰雹（黄色预警）");
        typeMap.put("11B16_YELLOW","霜冻（黄色预警）");
        typeMap.put("11B17_YELLOW","大雾（黄色预警）");
        typeMap.put("11B19_YELLOW","霾（黄色预警）");
        typeMap.put("11B20_YELLOW","雷雨大风（黄色预警）");
        typeMap.put("11B21_YELLOW","道路结冰（黄色预警）");
        typeMap.put("11B22_YELLOW","干旱（黄色预警）");
        typeMap.put("11B25_YELLOW","火险（黄色预警）");

        typeMap.put("11B85_YELLOW","雷雨强风（黄色预警）");
        typeMap.put("11B58_YELLOW","雷暴大风（黄色预警）");
        typeMap.put("11B52_YELLOW","雷雨大风（黄色预警）");
        typeMap.put("11B51_YELLOW","沙尘（黄色预警）");
        typeMap.put("11B37_YELLOW","地质灾害（黄色预警）");
        typeMap.put("11B86_YELLOW","低温凝冻（黄色预警）");
        typeMap.put("11D08_YELLOW","地质灾害气象风险（黄色预警）");
        typeMap.put("11A51_YELLOW","发布山洪灾害（黄色预警）");

        typeMap.put("11B41_YELLOW","森林草原火险（黄色预警）");

        typeMap.put("11B01_ORANGE","台风（橙色预警）");
        typeMap.put("11B03_ORANGE","暴雨（橙色预警）");
        typeMap.put("11B04_ORANGE","暴雪（橙色预警）");
        typeMap.put("11B05_ORANGE","寒潮（橙色预警）");
        typeMap.put("11B06_ORANGE","大风（橙色预警）");
        typeMap.put("11B07_ORANGE","沙尘暴（橙色预警）");
        typeMap.put("11B09_ORANGE","高温（橙色预警）");
        typeMap.put("11B11_ORANGE","干热风（橙色预警）");
        typeMap.put("11B14_ORANGE","雷电（橙色预警）");
        typeMap.put("11B15_ORANGE","冰雹（橙色预警）");
        typeMap.put("11B16_ORANGE","霜冻（橙色预警）");
        typeMap.put("11B17_ORANGE","大雾（橙色预警）");
        typeMap.put("11B19_ORANGE","霾（橙色预警）");
        typeMap.put("11B20_ORANGE","雷雨大风（橙色预警）");
        typeMap.put("11B21_ORANGE","道路结冰（橙色预警）");
        typeMap.put("11B22_ORANGE","干旱（橙色预警）");
        typeMap.put("11B25_ORANGE","火险（橙色预警）");

        typeMap.put("11B85_ORANGE","雷雨强风（橙色预警）");
        typeMap.put("11B58_ORANGE","雷暴大风（橙色预警）");
        typeMap.put("11B52_ORANGE","雷雨大风（橙色预警）");
        typeMap.put("11B51_ORANGE","沙尘（橙色预警）");
        typeMap.put("11B37_ORANGE","地质灾害（橙色预警）");
        typeMap.put("11B86_ORANGE","低温凝冻（橙色预警）");
        typeMap.put("11D08_ORANGE","地质灾害气象风险（橙色预警）");
        typeMap.put("11A51_ORANGE","发布山洪灾害（橙色预警）");

        typeMap.put("11B41_ORANGE","森林草原火险（橙色预警）");

        typeMap.put("11B01_RED","台风（红色预警）");
        typeMap.put("11B03_RED","暴雨（红色预警）");
        typeMap.put("11B04_RED","暴雪（红色预警）");
        typeMap.put("11B05_RED","寒潮（红色预警）");
        typeMap.put("11B06_RED","大风（红色预警）");
        typeMap.put("11B07_RED","沙尘暴（红色预警）");
        typeMap.put("11B09_RED","高温（红色预警）");
        typeMap.put("11B11_RED","干热风（红色预警）");
        typeMap.put("11B14_RED","雷电（红色预警）");
        typeMap.put("11B15_RED","冰雹（红色预警）");
        typeMap.put("11B16_RED","霜冻（红色预警）");
        typeMap.put("11B17_RED","大雾（红色预警）");
        typeMap.put("11B19_RED","霾（红色预警）");
        typeMap.put("11B20_RED","雷雨大风（红色预警）");
        typeMap.put("11B21_RED","道路结冰（红色预警）");
        typeMap.put("11B22_RED","干旱（红色预警）");
        typeMap.put("11B25_RED","火险（红色预警）");
        typeMap.put("11B86_REDE","低温凝冻（红色预警）");

        typeMap.put("11B85_RED","雷雨强风（红色预警）");
        typeMap.put("11B58_RED","雷暴大风（红色预警）");
        typeMap.put("11B52_RED","雷雨大风（红色预警）");
        typeMap.put("11B51_RED","沙尘（红色预警）");
        typeMap.put("11B37_RED","地质灾害（红色预警）");
        typeMap.put("11D08_RED","地质灾害气象风险（红色预警）");
        typeMap.put("11A51_RED","发布山洪灾害（红色预警）");

        typeMap.put("11B41_RED","森林草原火险（红色预警）");

        typeMap.put("10000","突发事件");
        typeMap.put("11000","自然灾害");
        typeMap.put("11A00","水旱灾害");
        typeMap.put("11A01","洪水");
        typeMap.put("11A02","内涝");
        typeMap.put("11A03","水库重大险情(包括垮坝事件)");
        typeMap.put("11A04","堤防重大险情(包括堤防决口事件)");
        typeMap.put("11A05","凌汛灾害");
        typeMap.put("11A51","山洪灾害事件");
        typeMap.put("11A52","农业干旱");
        typeMap.put("11A53","城镇缺水");
        typeMap.put("11A54","生态干旱");
        typeMap.put("11A10","农村人畜饮水困难");
        typeMap.put("11A99","其它水旱灾害");
        typeMap.put("11B00","气象灾害");
        typeMap.put("11B01","台风事件");
        typeMap.put("11B02","龙卷风事件");
        typeMap.put("11B03","暴雨事件");
        typeMap.put("11B04","暴雪事件(包括大雪事件)");
        typeMap.put("11B05","寒潮事件");
        typeMap.put("11B06","大风事件");
        typeMap.put("11B07","沙尘暴事件");
        typeMap.put("11B08","低温冻害事件");
        typeMap.put("11B09","巾高温事件");
        typeMap.put("11B10","热浪事件");
        typeMap.put("11B11","干热风");
        typeMap.put("11B12","下击暴流事件");
        typeMap.put("11B13","雪崩事件");
        typeMap.put("11B14","雷电事件");
        typeMap.put("11B15","冰雹事件(包括风雹)");
        typeMap.put("11B16","霜冻事件");
        typeMap.put("11B17","大雾事件");
        typeMap.put("11B18","低空风切变事件(可能引发航空器飞行事故)");
        typeMap.put("11B19","霾");
        typeMap.put("11B20","雷雨大风");
        typeMap.put("11B21","道路结冰");
        typeMap.put("11B22","干旱");
        typeMap.put("11B23","海上大风");
        typeMap.put("11B24","高温中暑");
        typeMap.put("11B25","森林火险");
        typeMap.put("11B26","草原火险");
        typeMap.put("11B27","冰冻");
        typeMap.put("11B28","空间天气");
        typeMap.put("11B29","重污染");
        typeMap.put("11B30","低温雨雪冰冻");
        typeMap.put("11B31","强对流");
        typeMap.put("11B32","臭氧");
        typeMap.put("11B33","大雪");
        typeMap.put("11B34","寒冷");
        typeMap.put("11B35","连阴雨");
        typeMap.put("11B36","渍涝风险");
        typeMap.put("11B37","地质灾害");
        typeMap.put("11B99","其它气象灾害");
        //后面添加
        typeMap.put("11B85","雷雨强风");
        typeMap.put("11B58","雷暴大风");
        typeMap.put("11B52","雷雨大风");
        typeMap.put("11B51","沙尘");
        typeMap.put("11B86","低温凝冻");
        typeMap.put("11D08","地质灾害气象风险");
        typeMap.put("Blue","蓝色预警");
        typeMap.put("Orange","橙色预警");
        typeMap.put("Yellow","黄色预警");
    }



    /**
     * 贵州省气象预警信息
     * @return
     */
     @SJob("parseMeteorologicalwarning")
    public  void parseMeteorologicalwarning(String taskId, String params) {
        System.out.println("贵州省气象预警信息: "+new Date());
        int pageNumber=1, pageSize=500;
        List<FetchData_emergency> warningBoList = new ArrayList<>();
        while (true) {
            Map<String, Object> params1 = new HashMap<>();
            params1.put("pageNumber", pageNumber);
            params1.put("pageSize", pageSize);
            String result = HttpUtils.getRequest("http://140.210.211.155:8089/datapi/meteorologicalwarning/query", params1);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject dataJson = jsonObject.getJSONObject("data");
            JSONObject pagerJson = dataJson.getJSONObject("pager");
            int pageCount = pagerJson.getInteger("pageCount");
            if (pageNumber > pageCount) {
                break;
            }

             Date day2 = new Date();
            //DateTime day2 = new DateTime("2023-07-01 12:34:23", DatePattern.NORM_DATETIME_FORMAT);
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


            day2.setHours(day2.getHours() - 24);
            Timestamp start =Timestamp.valueOf(sdf2.format(day2));
            JSONArray listJson = dataJson.getJSONArray("list");
            JSONArray listJsonNew =  listJson.stream().filter(item->((Timestamp)((JSONObject)item).getTimestamp("send_time")).compareTo(start)>0)
                    .collect(Collectors.toCollection(JSONArray::new));
           if(listJsonNew.isEmpty()) {
               pageNumber++;
               continue;
           }

            for (int i = 0; i < listJsonNew.size(); i++) {
                JSONObject item = listJson.getJSONObject(i);
                FetchData_emergency warningBo = new FetchData_emergency();
                warningBo.setReleasetime(((Timestamp) item.getTimestamp("send_time"))); //发布时间 sender
                warningBo.setInformationtitle(item.getString("headline"));//标题
                FetchData_emergency vo = wxSpiderEmergencyInformationService.fetch(Cnd.where(FetchData_emergency::getInformationtitle,"=",warningBo.getInformationtitle())
                        .and(FetchData_emergency::getReleasetime,"=",warningBo.getReleasetime()));
                if (ObjectUtil.isEmpty(vo)) {
                    try {
                                    String idStr = item.getString("identifier") + "-" + ((Timestamp) item.getTimestamp("send_time")).getTime();
                                    String wholeName = typeMap.get(item.getString("identifier"));

                                    if (StringUtils.isNotEmpty(wholeName)) {
                                        String[] areas = wholeName.split("，");
                                        warningBo.setProvince(areas[0]);
                                        warningBo.setCity(areas.length < 2 ? null : areas[1]);
                                        warningBo.setDistrict(areas.length < 3 ? null : areas[2]);
                                    }

                                    warningBo.setInformationchannels(item.getString("sender"));//气象局
                                    warningBo.setInformationcontent(item.getString("description"));//内容
                                    warningBo.setDisaster_class(typeMap.get(item.getString("severity")));
                                    warningBo.setInformationtitle(item.getString("headline"));//标题
                                    warningBo.setId(idStr);


                                    JSONObject addressInfo = null;
                                    JSONObject jsonresult = null;


                                    if (item.getString("headline").indexOf("省") > 0) {
                                        warningBo.setProvince(item.getString("headline").substring(0, item.getString("headline").indexOf("省") + 1));
                                    }
                                    warningBo.setCity("");
                                    if (item.getString("headline").indexOf("市") > 0) {
                                        warningBo.setCity(item.getString("headline").substring(0, item.getString("headline").indexOf("市") + 1));
                                    }
                                    warningBo.setDistrict("");
                                    if (item.getString("headline").indexOf("县") > 0) {
                                        warningBo.setDistrict(item.getString("headline").substring(0, item.getString("headline").indexOf("县") + 1));
                                    }
                                    if (item.getString("headline").indexOf("区") > 0) {
                                        warningBo.setDistrict(item.getString("headline").substring(0, item.getString("headline").indexOf("区") + 1));
                                    }
                                    if (item.getString("headline").indexOf("州") > 0) {
                                        warningBo.setDistrict(item.getString("headline").substring(0, item.getString("headline").indexOf("州") + 1));
                                    }


                                    if (warningBo.getProvince() == null || warningBo.getProvince().length() < 2 || warningBo.getProvince() == "") {
                                        ConcurrentHashMap map = new ConcurrentHashMap();
                                        if (warningBo.getCity() != null && warningBo.getCity().length() > 2) {
                                            map = AddressUtils.getLatAndLngByAddr(warningBo.getCity());
                                        }
                                        if (warningBo.getDistrict() != null && warningBo.getDistrict().length() > 2) {
                                            map = AddressUtils.getLatAndLngByAddr(warningBo.getDistrict());
                                        }
                                        if (map.get("lng") != null && map.get("lat") != null) {
                                            warningBo.setLongitude(String.valueOf(map.get("lng")));
                                            warningBo.setLatitude(String.valueOf(map.get("lat")));
                                            addressInfo = AddressUtils.getAddressInfo(String.valueOf(map.get("lng")), String.valueOf(map.get("lat")));
                                            if (addressInfo != null) {
                                                jsonresult = addressInfo.getJSONObject("result");
                                                if (jsonresult != null) {
                                                    JSONObject addressComponent = jsonresult.getJSONObject("addressComponent");
                                                    warningBo.setProvince(addressComponent.getString("province"));
                                                    String city = addressComponent.getString("city");
                                                    city = city.indexOf("省") > 0 ? city.substring(city.indexOf("省") + 1) : city;
                                                    warningBo.setCity(city);
                                                    warningBo.setDistrict(addressComponent.getString("county"));

                                                    if(warningBo.getDistrict()==null||warningBo.getDistrict().equals(""))
                                                        warningBo.setDistrict(addressComponent.getString("county"));
                                                    if((warningBo.getProvince()==null||warningBo.getProvince().equals(""))&&jsonresult.getString("formatted_address")!=null &&jsonresult.getString("formatted_address").indexOf("省")>0) {
                                                        warningBo.setProvince(jsonresult.getString("formatted_address").substring(0,jsonresult.getString("formatted_address").indexOf("省")+1));
                                                    }
                                                    warningBo.setDisaster_address(addressComponent.getString("province") + addressComponent.getString("city") + addressComponent.getString("county"));
                                                }
                                            }
                                        }
                                    }
                                    if(warningBo.getProvince()==null||warningBo.getProvince().equals("")) {
                                        warningBo.setProvince("贵州省");
                                    }

                                    if(warningBo.getDistrict().equals("白云区"))
                                    {
                                        warningBo.setProvince("贵州省");
                                        warningBo.setCity("贵州省");
                                    }

                                    if (warningBo.getDistrict().equals("贵州")) {
                                        warningBo.setDistrict(null);
                                    }
                                    if((warningBo.getCity()==null||warningBo.getCity().equals(""))&&warningBo.getDistrict()!=null)
                                    {
                                        warningBo.setCity(warningBo.getDistrict());
                                    }


                                    warningBo.setInformationmedia("贵州省气象局");

                                    warningBo.setDisaster_status("灾害");
                                    if(item.getString("event_type")!=null) {
                                        warningBo.setPicurl(item.getString("event_type")+"_"+item.getString("severity").toUpperCase() + ".png");
                                    }else{
                                        warningBo.setPicurl("other.png");
                                    }

                                   //  warningBo.setEventPicUrl(item.getString("severity"));

                                    String type = typeMap.get(item.getString("event_type"));
                                    warningBo.setDisaster_type(type);
                                    if (type != null && type.indexOf("事件") > 0) {
                                        warningBo.setDisaster_type(type.replaceAll("事件", ""));
                                    }
                                    //没有类型的再处理
                                    warningBo.setDisaster_type(warningBo.getDisaster_type()==null?"其他":warningBo.getDisaster_type());
                                    if(warningBo.getPicurl().contains("UNKNOWN")||warningBo.getDisaster_type().equals("其他")||warningBo.getPicurl().contains("11D08")||warningBo.getPicurl().contains("11D08")||warningBo.getPicurl().contains("11A51")||warningBo.getPicurl().contains("11B41")) //
                                    {
                                        warningBo.setPicurl("other.png");
                                    }
                                    //去掉异常类型
                                    if(warningBo.getDisaster_type().indexOf("(")>0)
                                    {
                                        warningBo.setDisaster_type(warningBo.getDisaster_type().substring(0,warningBo.getDisaster_type().indexOf("(")));
                                    }
                                    if(warningBo.getDisaster_type().indexOf("巾")>0)
                                    {
                                        warningBo.setDisaster_type(warningBo.getDisaster_type().replace("巾",""));
                                    }

                                    if(warningBo.getDisaster_type() ==null) {
                                        int startIndex = warningBo.getInformationtitle().indexOf("发布")+2;
                                        int endIndex = warningBo.getInformationtitle().indexOf("预警") - 2;
                                        // 进行截取
                                        if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
                                            warningBo.setDisaster_type( warningBo.getInformationtitle().substring(startIndex, endIndex));
                                            warningBo.setPicurl("other.png");
                                        } else {
                                            System.out.println("无法找到合适的开始和结束位置");
                                        }
                                    }
                                    if(warningBo.getDisaster_class() ==null) {
                                        int startIndex = warningBo.getInformationtitle().indexOf("预警")-2;
                                        int endIndex = warningBo.getInformationtitle().indexOf("预警") +2;
                                        // 进行截取
                                        if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
                                            warningBo.setDisaster_class( warningBo.getInformationtitle().substring(startIndex, endIndex));
                                        } else {
                                            System.out.println("无法找到合适的开始和结束位置");
                                        }
                                    }

                                    //不等于高温红色，干旱红色
                                    if(warningBo.getDisaster_class()!=null&&warningBo.getDisaster_class().equals("红色预警")&&!item.getString("type").equals("11B09_RED")&&!item.getString("type").equals("11B22_RED")) ////发邮件
                                    {
                                        List<String> sendUser=new ArrayList<>();
                                        // 发送内容
                                        String emileSend= propertiesProxy.get("email.Send");
                                        if(StrUtil.isNotBlank(emileSend)){
                                            sendUser=Arrays.asList(emileSend.split(","));
                                        }
                                        CompletableFuture[] cf = sendUser.stream().map(emile -> CompletableFuture.runAsync(() ->
                                                        emailSendServer.sendMsg("用户" ,warningBo.getInformationtitle(), emile, warningBo.getInformationcontent()), taskQueryExecutor)
                                                .thenApply(r -> r)).toArray(CompletableFuture[]::new);
                                    }
                                    //2607419919
                                    warningBo.setAddperson("祥云AI");
                                    warningBo.setAddphone("15555555555");
                                    warningBo.setIsshow("0");
                                    //添加人等
                                    Date day = new Date();
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    warningBo.setAddtime(sdf.format(day));

                                    // emergencyInfoList.add(warningBo);


                                    warningBoList.add(warningBo);
//                                    iWxSpiderEmergencyInformationService.insertBatch(warningBoList);


                            } catch(Exception e) {
                                e.printStackTrace();
                            }

                        }

            }
            pageNumber++;
        }
        if(CollectionUtil.isNotEmpty(warningBoList)){
          wxSpiderEmergencyInformationService.fastInsert(warningBoList);
        }
    }

}
